package com.pfzy.lib.utils;

import android.content.Context;
import android.content.res.Resources;
import android.os.Environment;
import android.util.TypedValue;
import android.view.WindowManager;

import java.lang.reflect.Field;
import java.text.DecimalFormat;

import static android.content.Context.WINDOW_SERVICE;

/**
 * 常用单位转换的辅助类
 */
public class DensityUtils {
    public static int dp2px(Context context, float dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dp, context.getResources().getDisplayMetrics());
    }
    public static int dp2px2(Context context, float dp) {
        return (int) ((context.getResources().getDisplayMetrics().density * dp) + 0.5f);
    }
    public static int dp2px(float dp) {
        float m = Resources.getSystem().getDisplayMetrics().density;
        return (int) ((dp * m) + 0.5f);
    }

    public static float pxToDp(int pxValue) {
        float m = Resources.getSystem().getDisplayMetrics().density;
        return (int) ((pxValue / m) + 0.5f);
    }

    public static int sp2px(Context context, float spVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
                spVal, context.getResources().getDisplayMetrics());
    }

    public static float px2dp(Context context, float pxVal) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (pxVal / scale);
    }

    public static float px2sp(Context context, float pxVal) {
        return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
    }

    public static int getScreenWidth(Context context) {
        WindowManager windowManager= (WindowManager) context.getSystemService(WINDOW_SERVICE);
        int width = windowManager.getDefaultDisplay().getWidth();
        return width;
    }

    public static int getScreenHeight(Context context) {
        WindowManager windowManager= (WindowManager) context.getSystemService(WINDOW_SERVICE);
        int height = windowManager.getDefaultDisplay().getHeight();
        return height;
    }

    public static final int getStatusBarHeight(Context context) {
        try {
            Class<?> c2 = Class.forName("com.android.internal.R$dimen");
            Object obj = c2.newInstance();
            Field field = c2.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return context.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
            return 75;
        }
    }

    public static final float px2dp(int px, Context context) {
        return px / context.getResources().getDisplayMetrics().density;
    }







    public static int sp2px(float spValue, Context context) {
        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) ((spValue * fontScale) + 0.5f);
    }
}
